package com.example.demo.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Exam;
import com.example.demo.entity.Sign;
import com.example.demo.entity.StudentPaper;
import com.example.demo.mapper.ExamMapper;
import com.example.demo.service.IExamService;
import com.example.demo.service.ISignService;
import com.example.demo.service.IStudentPaperService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * @descreption:
 * @author: xhr
 * @date: 2022/9/03
 */
@RestController
@RequestMapping("/exam")
public class ExamController {
    @Resource
    ExamMapper examMapper;
    @Resource
    private IExamService examService;

    @Resource
    private ISignService signService;

    @Resource
    private IStudentPaperService studentPaperService;
    //增
    @PostMapping
    public Result<?> save(@RequestBody Exam exam) {
        setState(exam);
        examMapper.insert(exam);
        return Result.success();
    }
    // 改
    @PutMapping
    public Result<?> update(@RequestBody Exam exam) {
        setState(exam);
        examMapper.updateById(exam);
        return Result.success();
    }
    //改考试状态
    private void setState(Exam exam){
        String time=exam.getTime();
        DateTime dateTime= DateUtil.parse(time,"yyyy-MM-dd HH:mm");
        Date now = new Date();
        if(DateUtil.compare(now,dateTime)<0){
            exam.setState("未开始");
        }else if(DateUtil.compare(now,DateUtil.offsetHour(dateTime,2))>0){
            exam.setState("已结束");
        }else {
            exam.setState("进行中");
        }
    }
    // 删
    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        examMapper.deleteById(id);
        return Result.success();
    }
    //全查（给其他vue用）高性能
    @GetMapping
    public Result<?> findAll(){
        return Result.success(examService.list());
    }
    //全(页)查
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "10") Integer pagesize,
                              @RequestParam(defaultValue = "1") Integer pagenum,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Exam> wrapper = Wrappers.<Exam>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Exam::getName, search);
        }
        Page<Exam> examPage = examMapper.selectPage(new Page<>(pagenum, pagesize), wrapper);
        for (Exam exam : examPage.getRecords()) {
            setState(exam);
        }
        return Result.success(examPage);
    }
    //是否开始考试与查询
    @GetMapping("/page/front")
    public Result<?> enableExam(@RequestParam(defaultValue = "") Integer userId) {
        List<Exam> examList = examService.list();
        if (userId!=null) {
            List<Sign> signList = signService.list(new QueryWrapper<Sign>().eq("user_id", userId));
            List<StudentPaper> studentPaperList=studentPaperService.list(new QueryWrapper<StudentPaper>().eq("user_id", userId));
            for (Exam exam : examList) {
                exam.setEnable(false);
                Integer examId = exam.getId();
                signList.stream().filter(sign -> sign.getExamId().equals(examId)).findFirst().ifPresent(sign -> {
                    exam.setEnable("审核通过".equals(sign.getState()));
                });
                studentPaperList.stream().filter(sp -> sp.getExamId().equals(examId)).findFirst().ifPresent(sp -> {
                    exam.setIsAnswer(true);
                });
                setState(exam);
            }
        }
        return Result.success(examList);
    }
}
